package com.java.androidmarket.aspect;

import com.java.androidmarket.entity.Result;
import com.java.androidmarket.utils.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * description:
 * author:张腾
 * date:2021-05-24
 */

@Aspect
@Component
public class RepeatSubmitAspect {

    @Autowired
    private RedisUtils redisUtils;

    @Pointcut("@annotation(noRepeatSubmit)")
    //表示切入点为所有加有noRepeatSubmit注解的方法
    public void pointCut(NoRepeatSubmit noRepeatSubmit){
    }

    @Around("pointCut(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp,NoRepeatSubmit noRepeatSubmit) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader("Token");
        String path = request.getServletPath();
        String key = token + path;

        if (redisUtils.get(key)==null) {
            redisUtils.set(key, UUID.randomUUID().toString(),5L, TimeUnit.SECONDS);
            return pjp.proceed();
        }else{
            System.out.println("重复请求");
            return Result.error("重复请求，请稍后再试");
        }

    }
}
